/**
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2022-03-22 14:22:26
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\utils\utils.js
 * @CIMC-V2
 */

import isArray from 'lodash/isArray'
import isObject from 'lodash/isObject'
import trim from 'lodash/trim'
import isString from 'lodash/isString'
import dayjs from 'dayjs'
import { componentId } from '@/utils/unique'
import { HASDATA_ACTION_ITEMS } from '@ve/utils/constant'

function translate(n) {
  return window.Translate(n)
}
/*******
 * @description:处理模块
 * @param {Array} list
 * @param {Object} formData
 * @return {*}
 */
export function setModels(list, formData = {}, rules = {}, formItems = {}) {
  list.forEach((v) => {
    if (['uiForm', 'uiCirculationForm', 'uiPdaForm'].includes(v.type)) {
      let _formData = {}
      let _formItems = {}
      let _rules = {}
      //查找下面所有form子元素
      if (v.list) {
        setModels(v.list, _formData, _rules, _formItems)
      }
      v.data.formItems = _formItems
      v.data.formData = _formData
      v.rules = _rules
    }
    if (['uiCirculationForm'].includes(v.type)) {
      let _formData = {}
      let _formItems = {}
      let _rules = {}
      //查找下面所有form子元素
      if (v.list[1]) {
        setModels(v.list[1].list, _formData, _rules, _formItems)
      }
      // console.log(_formData)
      v.data.formItems = _formItems
      v.data.formData = _formData
      v.rules = _rules
    }
    // uiGrid有个单独list 需要单独forEach
    if (['uiGrid', 'uiTabs', 'uiSplitpanes', 'uiQuotaBox', 'uiCollapse', 'uiFormLayout'].includes(v.type)) {
      v.list.forEach((vv) => {
        setModels(vv.list, formData, rules, formItems)
      })
    }
    // 一般组件
    if (['uiForm', 'uiPage', 'uiFlexbox', 'uiColumnBox', 'uiPdaForm', 'uiPdaGrid'].includes(v.type)) {
      if (v.list) {
        setModels(v.list, formData, rules, formItems)
      }
    }
    // 上下布局组件
    if (v._id.indexOf('uiLayoutBox') > -1) {
      if (v.list) {
        setModels(v.list, formData, rules, formItems)
      }
    }

    if (!v.type) return
    if (
      [
        'uiInput',
        'uiSwitch',
        'uiNumberInput',
        'uiDate',
        'uiRadio',
        'uiCheckbox',
        'uiSelect',
        'uiPdaSelect',
        'uiSelectPrinters',
        'uiSelectLayer',
        'uiDropdown',
        'uiUpload',
        'uiTimePicker',
        'uiCodemirror',
        'uiPdaInput',
        'uiPdaTimePicker',
        'uiCascader',
        'uiPrintTemplate',
        'uiPrintMark',
        'uiTransfer',
      ].includes(v.type) ||
      v.type.indexOf('uiSelectLayerNew') !== -1 ||
      v.type.indexOf('uiSelectDown') !== -1 ||
      // v.type.indexOf('uiDynamicForm') !== -1 ||
      v.type.indexOf('uiDate') !== -1 ||
      v.type.indexOf('uiInput') !== -1 ||
      v.type.indexOf('uiPdaInput') !== -1 ||
      v.type.indexOf('uiPdaSelect') !== -1 ||
      v.type.indexOf('uiPdaTimePicker') !== -1
    ) {
      // console.log('this.optionList===========', v)
      // models['username'] = '默认值'
      formData[v.extension.model.value] = getComponentDefaulType(v.type)
      if (v.type == 'uiSelectPrinters') {
        formData[v.extension.modelPaper.value] = getComponentDefaulType(v.type)
      }
      formItems[v._id] = v._id
      //使用验证
      // 添加选择组件不进行校验规则写入，防止错误必填的判断
      if (v.extension.rule && v.extension.rule.value && v.type.indexOf('uiSelectLayerNew') === -1) {
        rules[v.extension.model.value] = {
          required: true,
          trigger: 'blur',
        }
      }
      //扩展验证
      if (v.extension.extendRule && v.extension.extendRule.value) {
        //如果没设置则清空
        if (!v.extension.extendRule.value.ChangeSwitch) {
          delete rules[v.extension.model.value]
          return
        }
        const ruleArr = [],
          triggerArr = ['blur', 'change'],
          outType = ['phone', 'card', 'RegExp', 'number']

        //必填
        if (v.extension.extendRule.value.required) {
          let message = v.extension.extendRule.value.message || translate('Ve.utils.请输入必填信息')
          if (v.extension.extendRule.value.pattern || v.extension.extendRule.value.type) {
            message = translate('Ve.utils.请输入必填信息')
          }
          ruleArr.push({
            required: v.extension.extendRule.value.required || false,
            message: message,
            trigger: triggerArr,
          })
        }
        //处理最大最小值
        if (!['uiNumberInput'].includes(v.type) && (v.extension.extendRule.value.min > 0 || v.extension.extendRule.value.max > 0)) {
          let message =
            v.extension.extendRule.value.message ||
            `${translate('Ve.utils.长度在')} ${v.extension.extendRule.value.min || 0} ${translate('Ve.utils.到')}
            ${v.extension.extendRule.value.max || 0} ${translate('Ve.utils.个字符')}`
          if (v.extension.extendRule.value.pattern || v.extension.extendRule.value.type) {
            message = `${translate('Ve.utils.长度在')} ${v.extension.extendRule.value.min || 0} ${translate('Ve.utils.到')}
            ${v.extension.extendRule.value.max || 0} ${translate('Ve.utils.个字符')}`
          }
          ruleArr.push({
            min: v.extension.extendRule.value.min || 0,
            max: v.extension.extendRule.value.max || 0,
            message: message,
            trigger: triggerArr,
          })
        }
        //为null的时候处理
        if (v.extension.extendRule.value.type === 'null') {
          rules[v.extension.model.value] = ruleArr
          return
        }
        //处理type
        if (v.extension.extendRule.value.type && outType.includes[v.extension.extendRule.value.type]) {
          ruleArr.push({
            type: v.extension.extendRule.value.type,
            message: v.extension.extendRule.value.message,
            trigger: triggerArr,
          })
        }
        //处理正则
        if (v.extension.extendRule.value.pattern) {
          ruleArr.push({
            pattern: v.extension.extendRule.value.pattern,
            message: v.extension.extendRule.value.message,
            trigger: triggerArr,
          })
        }
        if (!ruleArr.length) {
          delete rules[v.extension.model.value]
          return
        }
        rules[v.extension.model.value] = ruleArr
      }
    }
  })
}

/*******
 * @description: 组件类型初始值
 * @param {Array} list
 * @param {String} id
 * @return {Object}
 */
export function getComponentDefaulType(name) {
  let _value = ''
  switch (name) {
    case 'uiInput':
      _value = ''
      break
    case 'uiDate':
      _value = ''
      break
    case 'uiSwitch':
      _value = false
      break
    case 'uiCheckbox':
      _value = ''
      break
    case 'uiWarehouseSelect':
      _value = []
      break
    case 'uiSlider':
      _value = 0
      break
    case 'uiNumberInput':
      _value = 0
      break
    case 'uiCascader':
      _value = ''
      break
  }
  return _value
}

/*******
 * @description: 通过id获取对应模块
 * @param {Array} list
 * @param {String} id
 * @return {Object}
 */
export function getModel(list, id, key = '_id') {
  return arraySearch(list, id, key, 'list')
}

/*******
 * @description: 删除指定模块
 * @param {Array} list
 * @param {String} id
 * @return {Array} 删除后返回的数组
 */
export function removeModule(list, id, key = '_id', children = 'list', child) {
  let _data = list.filter((x) => x[key] !== id)
  _data = _data.map((x) => {
    if (isArray(x)) {
      x = removeModule(x, id, key, children, child)
    }
    if (isObject(x) && x[children]) {
      x[children] = removeModule(x[children], id, key, children, child)
    }
    // 为删除else分支的逻辑动作
    if (child && isObject(x) && x[child]) {
      x[child] = removeModule(x[child], id, key, children, child)
    }
    return x
  })
  return _data
}

/*******
 * @description: 在数组中查找指定的项 ，支持多维数组 ，数组对象嵌套
 * @param {Array} list 数组
 * @param {*} id  要查询值
 * @param {String} key  查询的key
 * @param {String} children 子数组
 * @return {Array} 返回数组
 */
export function arraySearch(list, id, key = 'id', children = 'children') {
  if (!list || list.length == 0) return
  return (
    list.find((d) => d[key] == id) ||
    arraySearch(
      list.flatMap((d) => d[children] || []),
      id,
      key,
      children
    ) ||
    []
  )
}

/*******
 * @description:在数组中更新指定数据
 * @param {Array} list 数组
 * @param {*} id  需要查询的值
 * @param {String} key  需要查询的key
 * @param {String} children  子数组
 * @param {*} update  更新的数据 字符串/对象/数组...
 * @return {Array}  返回数组
 */
export function arrayUpdate(list, id, key = 'id', children = 'children', update) {
  if (list.length == 0) return
  list.forEach((v, i) => {
    if (v[key] == id) {
      list[i] = update
    }
    if (v && v[children]) {
      arrayUpdate(v[children], id, key, children, update)
    }
  })
  return list
}

/*******
 * @description:查找数组上一次父级
 * @param {Array} data 数组
 * @param {*} id  需要查询的值
 * @return {Object}  返回对象
 */
export function findPrevParent(data, query) {
  for (let i = 0; i < data.length; i++) {
    const { list } = data[i]
    const found = list.some(({ _id }) => _id === query) ? data[i] : list.length !== 0 ? findPrevParent(list, query) : null

    if (found) {
      return found
    }
  }

  return null
}

//获取预览页面info下list所有PageModules
export function recursiveList(data) {
  const res = []
  res.push(...data) // chilren插入结果数组
  for (const item of data) {
    // 遍历子元素，若包含children则递归调用
    if (item.list && item.list.length) {
      res.push(...recursiveList(item.list))
    }
  }
  return res
}

export function $(el) {
  return document.querySelector(el)
}

export function getParents(element, selector, includeElement = false) {
  const isWithSelector = selector !== undefined
  const elements = []
  let elem = element

  if (!includeElement) {
    elem = elem.parentElement
  }

  while (elem !== null) {
    if (elem.nodeType === Node.ELEMENT_NODE) {
      if (!isWithSelector || elem.matches(selector)) {
        elements.push(elem)
      }
    }

    elem = elem.parentElement
  }

  return elements
}

// 常量处理
export function processingConstant(_this, defaultValue) {
  if (!isString(defaultValue)) {
    // 如果值不是字符串类型 则直接返回原值 防止将值类型转换为字符串
    return defaultValue
  }
  let _defValue = trim(defaultValue)
  if (!_this.$store) {
    return _defValue
  }
  let _getConstant = _this.$store.getters['user/getConstant']
  let _value = ''
  switch (_defValue) {
    case '#USER_ID#':
      _value = _this.$store.getters['user/uid']
      break
    case '#TOKEN#':
      _value = _this.$store.getters['user/token']
      break
    case '#USER_NAME#':
      _value = _this.$store.getters['user/username']
      break
    case '#ORG_ID#':
      _value = _getConstant['#ORG_ID#']
      break
    case '#APP_ID#':
      _value = _this.$store.getters['user/appId']
      break
    case '#APP_CODE#':
      _value = _this.$store.getters['user/appCode']
      break
    case '#WH_ID#':
      _value = _getConstant['#WH_ID#']
      break
    case '#LANGUAGE_CODE#':
      _value = _this.$store.getters['user/language']
      break
    case '#AUTH_WH_ID#':
      _value = _getConstant['#AUTH_WH_ID#']
      break
    case '#AUTH_OWNER_ID#':
      _value = _getConstant['#AUTH_OWNER_ID#']
      break
    case '#AUTH_ORG_ID#':
      _value = _getConstant['#AUTH_ORG_ID#']
      break
    case '#AUTH_ORDER_RCV#':
      _value = _getConstant['#AUTH_ORDER_RCV#']
      break
    case '#AUTH_ORDER_SO#':
      _value = _getConstant['#AUTH_ORDER_SO#']
      break
    case '#AUTH_ORDER_CC#':
      _value = _getConstant['#AUTH_ORDER_CC#']
      break
    case '#AUTH_ORDER_ADJ#':
      _value = _getConstant['#AUTH_ORDER_ADJ#']
      break
    case '#AUTH_ORDER_MOV#':
      _value = _getConstant['#AUTH_ORDER_MOV#']
      break
    case '#AUTH_ORDER_TSF#':
      _value = _getConstant['#AUTH_ORDER_TSF#']
      break
    case '#AUTH_ORDER_FRZ#':
      _value = _getConstant['#AUTH_ORDER_FRZ#']
      break
    case '#CURRENT_DATE#':
      _value = dayjs().format('YYYY-MM-DD')
      break
    case '#CURRENT_DATETIME#':
      _value = dayjs().format('YYYY-MM-DD HH:mm:ss')
      break
    case '#DECI_CONTROL#':
      _value = _getConstant['#DECI_CONTROL#']
      break
    case '#UNIQUE_VALUE#':
      _value = componentId(16)
      break
    default:
      _value = _defValue
      break
  }
  return _value
}

/*******
 * @description:生成符合格式的时间组件数据
 * @param {String} type 时间类型
 * @return {String || Array}  返回对象
 */
export function getDefaultDate(type) {
  const formatDate = (dateVal) => {
    const fullYear = dateVal.getFullYear()
    const month = dateVal.getMonth() + 1 < 10 ? `0${dateVal.getMonth() + 1}` : dateVal.getMonth() + 1
    const day = dateVal.getDate() < 10 ? `0${dateVal.getDate()}` : dateVal.getDate()
    const hours = dateVal.getHours() < 10 ? `0${dateVal.getHours()}` : dateVal.getHours()
    const minutes = dateVal.getMinutes() < 10 ? `0${dateVal.getMinutes()}` : dateVal.getMinutes()
    const seconds = dateVal.getSeconds() < 10 ? `0${dateVal.getSeconds()}` : dateVal.getSeconds()
    return `${fullYear}-${month}-${day} ${hours}:${minutes}:${seconds}`
    // return `${dateVal.getFullYear()}-${
    //   dateVal.getMonth() + 1
    // }-${dateVal.getDate()} ${dateVal.getHours()}:${dateVal.getMinutes()}:${dateVal.getSeconds()}`
  }
  if (type === 'now') {
    return formatDate(new Date())
  } else if (type === 'yesterday') {
    let yesterday = new Date()
    yesterday.setTime(yesterday.getTime() - 3600 * 1000 * 24)
    return formatDate(yesterday)
  } else if (type === 'oneDay') {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24)
    return [formatDate(start), formatDate(end)]
  } else if (type === 'threeDay') {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
    return [formatDate(start), formatDate(end)]
  } else if (type === 'week') {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    return [formatDate(start), formatDate(end)]
  } else if (type === 'month') {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    return [formatDate(start), formatDate(end)]
  } else if (type === 'year') {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
    return [formatDate(start), formatDate(end)]
  }
}

/*******
 * @description:根据组件Id查找组件
 * @param {String} modelId 组件Id
 * @param {String} modelTree 组件树
 * @return {null || Object}  返回对象
 */
export function getModelByModelTree(modelId, modelTree) {
  let _model = null
  const eachFunc = (obj) => {
    if (obj._id === modelId) {
      _model = obj
      return
    }
    obj.pageModules &&
      obj.pageModules.forEach((item) => {
        eachFunc(item)
      })
    obj.list &&
      obj.list.forEach((item) => {
        eachFunc(item)
      })
  }
  eachFunc(modelTree)
  return _model
}

/*******
 * @description:替换值中的变量
 * @param {String} str 要替换的字符串
 * @param {String} dataObj 变量取值对象
 * @return {String}  返回字符串
 */
export function replaseRegVariable(str, dataObj) {
  const staticList = str.split(/#{.*?}/gi)
  const variableList = str.match(/#{(.+?)\}/g)
  // console.log(variableList)
  let returnStr = ''
  variableList && variableList.forEach((variableItem, index) => {
    let variableContent = ''
    variableItem = trim(variableItem.slice(2, -1))
    variableContent = dataObj[variableItem]
    staticList.splice(index * 2 + 1, 0, variableContent)
  })
  returnStr = staticList.join('')
  return returnStr
}
/*******
 * @description:级联选中最后一级回显
 * @param {Array} options 级联下拉数据（树形）
 * @param {String} last 选中最后一级
 * @param {String} childLevelKey 包含子级的key值一般为Children
 * @param {String} selectKey 选中的值在下拉数据中的key
 * @param {String} pidKey 选中的值的父级key
 * @return {Array}  返回数组
 */
export function getCascaderShow(options, last, childLevelKey, selectKey, pidKey) {
  const lastList = last.split(',')
  let _list = []
  const getPid = (list) => {
    for (let i = 0; i < list.length; i++) {
      if (lastList.find((el) => el == list[i][selectKey])) {
        let result = findParentNodes(options, list[i][pidKey], selectKey)
        _list.push([...result, list[i][selectKey]])
      }
      if (list[i][childLevelKey] && list[i][childLevelKey].length > 0) {
        getPid(list[i][childLevelKey])
      }
    }
  }
  if (options) {
    getPid(options)
  }
  return _list
}
function findParentNodes(tree, id, key) {
  let nodes = []
  const find = (node) => {
    if (node[key] == id) {
      nodes.unshift(node[key])
      return true
    }
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        const found = find(node.children[i])
        if (found) {
          nodes.unshift(node[key])
          return true
        }
      }
    }
    return false
  }
  tree.forEach((e) => {
    find(e)
  })
  return nodes
}
// 表单组件判断方法
const moduleIsFormItem = (type) => {
  return (
    [
      'uiInput',
      'uiSwitch',
      'uiNumberInput',
      'uiDate',
      'uiRadio',
      'uiCheckbox',
      'uiSelect',
      'uiPdaSelect',
      'uiSelectPrinters',
      'uiSelectLayer',
      'uiDropdown',
      'uiUpload',
      'uiTimePicker',
      'uiCodemirror',
      'uiPdaInput',
      'uiPdaTimePicker',
      'uiCascader',
      'uiPrintTemplate',
      'uiPrintMark',
      'uiTransfer',
    ].includes(type) ||
    type.indexOf('uiSelectLayerNew') !== -1 ||
    type.indexOf('uiSelectDown') !== -1 ||
    // type.indexOf('uiDynamicForm') !== -1 ||
    type.indexOf('uiDate') !== -1 ||
    type.indexOf('uiInput') !== -1 ||
    type.indexOf('uiPdaInput') !== -1 ||
    type.indexOf('uiPdaSelect') !== -1 ||
    type.indexOf('uiPdaTimePicker') !== -1
  )
}

// 筛选事件
const filterEvents = (eventList, filter) => {
  const useEvent = []
  eventList.forEach((ei) => {
    const events = []
    ei.list.forEach((i) => {
      if (filter.indexOf(i.event) > -1) events.push(i)
    })
    if (events.length) useEvent.push({ name: ei.name, list: events })
  })
  return useEvent
}

// 根据组件类型筛选可使用的事件
export function getModuleUsableEvents(eventList, moduleType) {
  console.log('根据类型筛选事件', eventList, moduleType)
  const isFormItem = moduleIsFormItem(moduleType)
  let events = []
  if (isFormItem) {
    // 表单项组件有值改变、回车事件
    events = ['onChange', 'onEnterKeyUp', 'onLoad']
  } else if (moduleType === 'uiTable') {
    // 表格组件有表格事件与载入时事件
    events = ['onTableClick', 'onTableDblClick', 'onTableSelectChang', 'onLoad']
  } else if (moduleType === 'uiButton') {
    // 按钮组件有点击和回车事件
    events = ['onClick', 'onEnterKeyUp', 'onLoad']
  } else if (moduleType === 'uiPrint') {
    // 打印组件只有打印点击事件
    events = ['onPrintClick', 'onLoad']
  } else if (['uiTabs', 'uiCollapse', 'uiDropdown'].indexOf(moduleType) > -1) {
    // tab也 折叠面板 下拉菜单有激活切换、载入时
    events = ['onPrintClick', 'onLoad']
  } else {
    // 其他组件有点击和双击和载入时事件
    events = ['onClick', 'onDbClick', 'onLoad']
  }
  return filterEvents(eventList, events)
}

// 获取动作数据
export function getActionData(_this, moduleId, actionId) {
  let actionData = {}
  const actionsData = _this.$store.getters['actionDatas/getActionsData'][moduleId]
  if (actionsData) {
    actionData = actionsData[actionId] || {}
  }
  return actionData
}

// 查找动作属于的事件动作列表
export const findBelongActions = (_this) => {
  let actionList = []
  const cacheInteractions = _this.$store.getters['diyInteraction/getCacheInteractions']
  const selectedAction = _this.$store.getters['diyInteraction/getSelectActionId']
  cacheInteractions.forEach((i) => {
    const eachFunc = (actionItem, actions) => {
      if (actionItem._id === selectedAction) actionList = actions
      actionItem.actions && actionItem.actions.forEach((i) => eachFunc(i, actions))
      actionItem.elseActions && actionItem.elseActions.forEach((i) => eachFunc(i, actions))
    }
    i.actions.forEach((ai) => {
      eachFunc(ai, i.actions)
    })
  })
  return actionList
}

// 组织动作数据源可选择的动作
export const getDataSourceActions = (_this) => {
  // 先获取所有动作列表
  const actions = findBelongActions(_this)
  // 再筛选有数据存储的动作
  const actionList = []
  const eachFunc = (actionItem, parent) => {
    if (HASDATA_ACTION_ITEMS.indexOf(actionItem.event) > -1) {
      parent.push({
        label: actionItem.name,
        value: actionItem._id,
        isLeaf: true,
      })
    } else if (['logicJudge', 'pdaLogicJudge'].indexOf(actionItem.event) > -1) {
      // 逻辑判断动作需要组织子级
      const logicActionObj = {
        label: actionItem.name,
        value: actionItem._id,
        disabled: false,
        children: [
          {
            label: 'Y',
            value: 'y',
            disabled: false,
            children: [],
          },
          {
            label: 'N',
            value: 'N',
            disabled: false,
            children: [],
          },
        ],
      }
      parent.push(logicActionObj)
      // 通过动作循环
      actionItem.actions.forEach((i) => eachFunc(i, logicActionObj.children[0].children))
      // 未通过动作循环
      actionItem.elseActions && actionItem.elseActions.forEach((i) => eachFunc(i, logicActionObj.children[1].children))
      if (!logicActionObj.children[0].children.length) logicActionObj.children[0].disabled = true
      if (!logicActionObj.children[1].children.length) logicActionObj.children[1].disabled = true
    }
  }
  actions && actions.forEach((ai) => eachFunc(ai, actionList))
  return actionList
}

// 根据类型整理组件选择树
export const trimModuleTree = (moduleTree, types) => {
  console.log(moduleTree, types)
  const eachFunc = (moduleObj, parent) => {
    let parentObj = parent
    const moduleItem = {
      name: moduleObj.name,
      _id: moduleObj._id,
      list: [],
    }
    if (types.indexOf(moduleObj.type) > -1) {
      parent.push(moduleItem)
      parentObj = moduleItem.list
    } else if ([1, 2, 3, 4].indexOf(moduleObj.type) > -1) {
      // 图层级别显示但禁用
      moduleItem.disabled = true
      parent.push(moduleItem)
      parentObj = moduleItem.list
    }

    moduleObj.list && moduleObj.list.forEach((i) => eachFunc(i, parentObj))
  }
  const moduleList = []
  moduleTree.forEach((i) => {
    eachFunc(i, moduleList)
  })

  return moduleList
}

// 根据路径取值
export const getDataByPath = (dataObj, field) => {
  let rData = dataObj[field]
  let cacheObj = null
  if (field.indexOf('->') !== -1) {
    const fieldList = field.split('->')
    cacheObj = dataObj
    fieldList.forEach((fieldItem) => {
      // 如果没有后续值则不继续往下取值
      if (cacheObj[trim(fieldItem)] === undefined) return
      rData = cacheObj = cacheObj[trim(fieldItem)]
    })
  }
  return rData
}

// 根据字段在列表数据中查找对象
export const findListItem = (obj, field, list) => {
  if (!field) return list[0]
  let fieldList = [field]
  if (field.indexOf(',') > -1) {
    fieldList = field.split(',')
  }
  let o = list[0]
  list.forEach((i) => {
    let flag = true
    fieldList.forEach((ii) => {
      ii = trim(ii)
      if (obj[ii] !== i[ii]) flag = false
    })
    if (flag) o = i
  })
  return o
}
